<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>JS校验</title>
</head>
<body>

    <div style="float: left;margin-right: 5px;">code: </div>
    <div style="float: left;margin-right: 10px;" id="code-output"></div>
    <input type="text" id="code-input" placeholder="请输入验证码">
    <button onclick="verifyCode()">提交</button>
</body>
<script>
var code;
function createCode() {
    code = '';
    var codeLength = 4; //验证码长度
    var selectChar = new Array(0,1,2,3,4,5,6,7,8,9,
                                'a','b','c','d','e','f','g','h','i','j',
                                'k','l','m','n','o','p','q','r','s','t',
                                'u','v','w','x','y','z','A','B','C','D',
                                'E','F','G','H','I','J','K','L','M','N',
                                'O','P','Q','R','S','T','U','V','W','X','Y','Z');
    for (var i = 0; i < codeLength; i++) {
        var index = Math.floor(Math.random() * 62); //取得随机数的索引（0~35）
        code += selectChar[index]; //根据索引取得随机数加到code上
    }
    let myDiv = document.getElementById("code-output");
    myDiv.innerText = code;
    //document.getElementById('code-input').value = code; //把code值赋给验证码文本框
}

function getQueryString(name) {
  	let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  	let r = window.location.search.substr(1).match(reg);
  	if (r != null) {
      	return unescape(r[2]);
  	};
  	return null;
}

function verifyCode() {
    //获取用户输入的验证码并与生成的验证码进行比较
    var inputCode = document.getElementById('code-input').value;
    if(inputCode.length <= 0) {
        alert('请输入验证码！');
    } else if(inputCode.toUpperCase() != code.toUpperCase()) {
        alert("验证码输入有误！");
        createCode();//刷新验证码
    }else {
        //alert('验证码正确！');
       var url = getQueryString("srcUrl");
        window.location.href = url;
    }
}
createCode()
</script>
</html>